package com.jr.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/* 未登录，拦截访问！
*
* 控制 哪些 url 不拦截，直接放行
*     哪些 url 拦截，驳回
*
* 1.先判断session里，有没有 user的key
*   ---如果没有，说明没登录：reg.jsp , /reg , login.jsp , /login 是放行的(注册和登录)
*                        除此之外，都拦截
*   ---如果有，路径都放行！
* 2.
* */

/*@WebFilter("/*")*/  /* "/*"是因为所有的操作都得过来判断有没有登录*/
public class InterceptFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    String[] urls = {"reg.jsp","reg","login.jsp","login"};
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Object user = request.getSession().getAttribute("user");
        if(user==null){ //没登录
            if(checkUrl(request)){
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                //驳回，返到登录页
                ((HttpServletResponse)servletResponse).sendRedirect("/aaa/login.jsp");
            }
        }else{ //登录成功
            //放行---调用执行链里的下一个执行方法
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    public boolean checkUrl(HttpServletRequest request){
        //1.先获得请求地址：
        String requestURI = request.getRequestURI();
        int  index = requestURI.lastIndexOf("/")+1;
        String mName = requestURI.substring(index);
        for(String s:urls){
            if(s.equals(mName)){
                return true;
            }
        }
        return false;
    }


    @Override
    public void destroy() {}


}
